#!/usr/bin/perl
#mkfsd.pl

require "/sbin/webmin/syslog_w.pl";

my ($log_ev, $log_msg, $diskminor);
$diskminor = "diskman";

my $mddev=$ARGV[0];
my $voldir=$ARGV[1];
$voldir =~ /(volume\d+)/;
my $volpath = $1;

#my $mkfs_lock='/var/nas/lock/mkfsd';
my $mkfs_lock_new='/var/nas/lock/mkfsd_new';

# add_voltab(volname, mddev, status)
sub add_voltab
{
	my ($volname, $line, @newtab);

	$volname = $_[0];
	$mddev = $_[1];
	$status = $_[2];

	my $voltab = '/etc/nas/voltab';
	open(VOLTAB, $voltab);
	while ($line = <VOLTAB>) {
		my $tmp = $line;
		$tmp =~ s/\r|\n//g;
		$tmp =~ s/#.*$//g;

		my @t;
		@t = split(/\s+/, $tmp);
		if ($volname eq $t[0]) {
			next;
		}
		push (@newtab, $line);
	}
	close(VOLTAB);


	push (@newtab, join("\t", ($volname, $mddev, $status, "\n")));

	open(VOLTAB, "> $voltab");
	foreach $line (@newtab) {
		print VOLTAB $line;
	}

	close(VOLTAB);
}

$out = `mkfs.ext3 -q $mddev 2>&1`;

if ($?) {
	#failed
	$log_ev = 15007;
	$log_msg= "Format $volname error.";
	nas_syslog($diskminor, 'naslog_info', $log_ev, $log_msg);
	GOTO ABORT;
}

if (!-d $voldir) {
	mkdir $voldir;
	$out = `chmod a+rwx $voldir 2>&1`;
}

$out = `mount -o usrquota -o grpquota -o async -o noatime $mddev $voldir 2>&1`;

if ($?) {
	#log
	$log_ev = 15008;
	$log_msg= "Format $volname error, cannot mount the volume.";
	nas_syslog($diskminor, 'naslog_info', $log_ev, $log_msg);
	goto ABORT;
}


$out = `quotacheck -u -g -f -n $voldir 2>&1`;
if ($?) {
	#log
	$log_ev = 15009;
	$log_msg= "Format $volname error, cannot create quota in the volume(quotacheck error).";
	nas_syslog($diskminor, 'naslog_info', $log_ev, $log_msg);
	goto ABORT;
}

$out = `quotaon -u -g $voldir 2>&1  && setquota -t 604800 604800 $voldir 2>&1 `;
if ($?) {
	#log
	$log_ev = 15010;
	$log_msg= "Format $volname error, cannot create quota in the volume(quotaon error).";
	nas_syslog($diskminor, 'naslog_info', $log_ev, $log_msg);
	goto ABORT;
}

#add_voltab($volpath, $mddev, 'normal');

$log_ev = 15011;
$log_msg= "Format $volname ok";
nas_syslog($diskminor, 'naslog_info', $log_ev, $log_msg);

#-------------no use in 3w disk management-----------------#
#open (MKFSDEV, "/tmp/ezmkfsdev.info");
#while (<MKFSDEV>) {
#	chomp;
#	/(\S+)(\d+)/;
#	$out = `sfdisk --change-id $1 $2 fd 2>&1`;
#}
#close (MKFSDEV);
$out = `rm -f /tmp/ezmkfsdev.info 2>&1`;
#----------------------------------------------------------#

ABORT:
	$out= `rm -f $mkfs_lock_new 2>&1`;
	exit 0;



#add an entry in voltab
